package org.runecore.file;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
import java.util.logging.Logger;

import org.runecore.Launch;
import org.runecore.util.LogHandler;

/**
 * RuneCore
 * Aug 26, 2011
 * @author Harry Andreas<Harry@RuneCore.org>
 */
public class FileSystem {
	
	/**
	 * A <code>File</code> containing the path
	 * to the application environment
	 */
	public final File FILE_SYSTEM_PATH = new File("./data/env/");
	
	/**
	 * A <code>HashMap</code> containing a 'map' of files
	 * that are currently loaded within the environment
	 */
	private final Map<String, File> MAPPED_FILES = new HashMap<String, File>();
	
	/**
	 * The <code>Logger</code> for logging messages to the console
	 */
	private Logger logger = Logger.getLogger(FileSystem.class.getName());
	
	/**
	 * Constructor
	 */
	public FileSystem() {
		logger.addHandler((LogHandler)Launch.getEnv().getAttribute("logHandler"));
		logger.info("Attempting to map file system");
		mapSystem();
		logger.info("Mapped "+MAPPED_FILES.size()+" files into memory.");
	}
	
	/**
	 * Map's the entire file system
	 */
	private void mapSystem() {
		addFiles(FILE_SYSTEM_PATH.listFiles());
	}
	
	/**
	 * Gets a file by name
	 * @param name The name of the file
	 * @return The file instance
	 */
	public File getFileByName(String name) {
		for(String s : MAPPED_FILES.keySet()) {
			if(s.toLowerCase().contains(name.toLowerCase())) {
				return MAPPED_FILES.get(s);
			}
		}
		return null;
	}
	
	/**
	 * Adds an array of <code>File</code>'s 
	 * to the Mapped File's <code>HashMap</code>
	 * @param files
	 */
	private void addFiles(File[] files) {
		for(File file : files) {
			if(file.isDirectory()) {
				addFiles(file.listFiles());
				continue;
			} 
			MAPPED_FILES.put(file.getPath().replace("." +
					""+File.separator+"data"+File.separator+"env"+File.separator, "")
					.replace(File.separator, "/"), file);
		}
	}
	
	/**
	 * 
	 * @param location
	 */
	public ArrayList<File> generateFileList(String location) {
		ArrayList<File> list = new ArrayList<File>();
		for(String s : MAPPED_FILES.keySet()) {
			if(s.contains(location)) {
				list.add(MAPPED_FILES.get(s));
			}
		}
		return list; 
	}

}